<template>
	<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="1000px" @close="clean">
		<div class="dialog-content">
			<pre class="dialog-pre" v-for="log in state.logs">{{ log }}</pre>
		</div>
	</el-dialog>
</template>

<script setup lang="ts" name="logDialog">
import { reactive, onMounted, nextTick } from 'vue';
import { createWebsocket } from '/@/api/ws';

const state = reactive({
	logs: [],
	socket: undefined,
	dialog: {
		isShowDialog: false,
		type: '',
		title: '日志',
	},
});

const props = defineProps({
	row: {
		type: Object,
		default: () => {},
	},
});

// 打开弹窗
const openDialog = async () => {
	state.dialog.isShowDialog = true;
	await nextTick(() => {
		state.dialog.title = '任务: ' + props.row.jobName + ' 构建编号: ' + props.row.buildNumber + ' 日志';
		getData();
	});
};

const getData = async () => {
	state.logs = [];
	const onOpen = function () {
		let queryData = {
			job_name: props.row.jobName,
			build_id: props.row.buildNumber,
		};
		// 发送消息给服务器
		state.socket.send(JSON.stringify(queryData));
	};

	const onMessage = function (event) {
		const message = event.data;
		state.logs.push(message);
	};
	state.socket = createWebsocket('ws://localhost:8080/jenkins/wsBuildLog', onOpen, onMessage);
};

const clean = () => {
	state.logs = [];
	if (state.socket) {
		if (state.socket.readyState !== WebSocket.CLOSED && state.socket.readyState !== WebSocket.CLOSING) {
			state.socket.send('close');
		}
		nextTick(() => {
			state.socket.close();
			state.socket = undefined;
		});
	}
};

// 页面加载时
onMounted(() => {
	// getData();
});

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style lang="scss" scoped>
.dialog-pre {
	white-space: pre-wrap;
	word-wrap: break-word;
}

.dialog-content {
	max-height: 60vh; /* 5设置最大高度 */
	overflow-y: auto; /* 添加垂直滚动条 */
}

.cus:deep(.el-overlay .el-overlay-dialog) {
	align-items: normal;

	.el-dialog {
		margin: 15vh auto !important;
	}
}
</style>
